/*
 *  IOController.cpp
 *  initiativeTracker
 *
 *  Created by Sam Jaffe on 5/7/12.
 *  Copyright 2012 WPI. All rights reserved.
 *
 */

#include <iostream>
#include <fstream>
#include <memory>
#include <boost/algorithm/string.hpp>
#include "FIOController.h"
#include "XIOController.h"

void hashMob(const std::string path, std::unordered_map<std::string, NPC*> storedMobs) {
    std::ifstream file(path.c_str());
    std::string name, strLine;
    std::vector<std::string> ss;
    
    NPC* c;
    
    int x = 0;
    
    if (!file.is_open()) return;
    while (file.good()) {
        std::getline(file, strLine);
        if (x == 0) {
                name = strLine;
        }
        else if (x == 1) {
                c = new NPC(strLine.substr(13) == "true");
                c->setName(name);
        }
        else if (x == 2) {
                boost::split(ss, strLine, boost::is_any_of(","));
                unsigned short hp = atoi(ss[0].c_str());
                c->setHp(hp);
                c->setHp_max(hp);
                c->setAc(atoi(ss[1].c_str()));
                c->setFort(atoi(ss[2].c_str()));
                c->setRef(atoi(ss[3].c_str()));
                c->setWill(atoi(ss[4].c_str()));
                break;
        }
    }
}

void makeMobFile(const NPC* npc) {
    std::ofstream file(("Mob/" + npc->getShortName() + ".mob").c_str());
    if (!file.is_open()) return;
    
    file << npc->toXML();
    
    file.close();
}

void export_init(const std::string tracker, const InitTracker* init) {
    std::ofstream file((tracker + ".initiative").c_str());
    int i;
    if (!file.is_open()) return;
    
    file << "<data id='" << tracker << "' turn='" << 
            (init->getTurn()) << "' next='" <<
            (init->getNext()) << "'>";
    
    std::shared_ptr<Character> c;
    while ((c = init->get(i++)) != 0)
        file << c->toXML();
    
    file << "</data>";
    file.close();
}

std::shared_ptr<InitTracker> import(const std::string tracker, XML_Handler* handler) {
    std::string data;
    std::string line;
    std::ifstream file((tracker + ".initiative").c_str());
    
    if (!file.is_open()) return 0;
    while (file.good()) {
        std::getline(file, line);
        data += line;
    }
    
    std::shared_ptr<InitTracker> itracker(new InitTracker(tracker));
    
    process_download(itracker, new Message(tracker, handler));
    
    return itracker;
}
